package com.lengyu.iottransfer.gateway.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lengyu.iottransfer.gateway.entity.User;
import com.lengyu.iottransfer.gateway.security.rest.dto.JwtUser;
import com.lengyu.iottransfer.gateway.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Authenticate a user from the database.
 */
@Component("userDetailsService")
public class UserModelDetailsService implements UserDetailsService {

   private final Logger log = LoggerFactory.getLogger(UserModelDetailsService.class);

   @Autowired
   private IUserService userService;

   @Override
   @Transactional
   public JwtUser loadUserByUsername(final String username) {
      log.debug("Authenticating user '{}'", username);

      //调用usersMapper方法，根据用户名查询数据库
      QueryWrapper wrapper = new QueryWrapper();
      // where username=?
      wrapper.eq("username",username);
      User user = userService.getOne(wrapper,false);
      //判断
      if(user == null) {//数据库没有用户名，认证失败
         throw  new UsernameNotFoundException("用户名不存在！");
      }
//      List<GrantedAuthority> auths =
//              AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
      //从查询数据库返回users对象，得到用户名和密码，返回
      return JwtUser.makeJwtUser(user,"admin");

   }

}
